package com.subframe7536.sa.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.subframe7536.sa.entity.LoginEntity;
import com.subframe7536.sa.entity.MyUserdetailEntity;
import com.subframe7536.sa.mapper.LoginMapper;
import com.subframe7536.sa.utils.RedisCacheUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author subframe7536
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private RedisCacheUtil cache;

    @Resource
    private ThreadPoolTaskExecutor executor;

    @PostConstruct
    @DS("slave")
    public void init() {
        executor.execute(() -> {
            List<LoginEntity> list = new LambdaQueryChainWrapper<>(loginMapper).list();
            list.forEach((entity) -> cache.set("info" + entity.getPhone(), entity));
        });
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginEntity one = (LoginEntity) cache.get("info" + username);
//        if (one == null) {
//            one = new LambdaQueryChainWrapper<>(loginMapper).eq(LoginEntity::getPhone, username).one();
//        }
        if (one == null) {
            throw new UsernameNotFoundException("没有该用户的信息");
        }
        ArrayList<String> list = new ArrayList<>();
        list.add("test");
        return new MyUserdetailEntity(one, list);
    }

}
